package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.redis.JobRedisKey;
import cn.wolfcode.web.feign.SeckillProductFeignApi;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Setter
@Getter
@RefreshScope
@Slf4j
@Component
public class SeckillProductListJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    SeckillProductFeignApi seckillProductFeignApi;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public void execute(ShardingContext shardingContext) {
        dowork(shardingContext.getShardingParameter());
    }

    private void dowork(String time) {
        //远程调用秒杀服务把数据查询出来
        /**
         * result情况：
         *  1.秒杀服务直接挂掉，直接走降级的方法 SeckillProductFeignFallback ，返回值是null
         *  2.正常情况 {code:200,msg:"操作成功"},data:List<SeckillProductVo>
         *  3.异常情况 {code:50xxx,msg:"错误信息"}
         */
        Result<List<SeckillProductVo>> seckillProductResult = seckillProductFeignApi.queryCurrentList(Integer.valueOf(time));
        if (seckillProductResult == null && seckillProductResult.hasError()) {
            log.info("查询结果异常");
            return;
        }
        List<SeckillProductVo> seckillProductVos = seckillProductResult.getData();
        if (seckillProductVos != null && seckillProductVos.size() > 0) {
            String seckillProductKey = JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time);
            String stockCountKey = JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time);
            for (SeckillProductVo seckillProductVo : seckillProductVos) {
                //查询出来的数据放到redis中
                redisTemplate.opsForHash().put(seckillProductKey, String.valueOf(seckillProductVo.getId()), JSON.toJSONString(seckillProductVo));
                redisTemplate.opsForHash().put(stockCountKey, String.valueOf(seckillProductVo.getId()), String.valueOf(seckillProductVo.getStockCount()));
            }
        }
    }
}
